import Cookies from 'js-cookie'

const TokenKey = 'fp-token'

export function getToken() {
  // 首先尝试从Cookie获取
  let token = Cookies.get(TokenKey)
  
  // 如果Cookie中没有，尝试从localStorage获取
  if (!token) {
    token = localStorage.getItem(TokenKey)
    console.log('从localStorage获取token:', token)
  } else {
    console.log('从Cookie获取token:', token)
  }
  
  return token
}

export function setToken(token) {
  if (!token) {
    console.warn('尝试设置空token')
    return false
  }
  
  console.log('设置token:', token.substring(0, 20) + '...')
  
  try {
    // 尝试设置Cookie
    const cookieResult = Cookies.set(TokenKey, token, { 
      expires: 7, // 7天过期
      secure: false, // 开发环境不需要HTTPS
      sameSite: 'lax' // 允许跨站请求
    })
    
    // 同时设置localStorage作为备用
    localStorage.setItem(TokenKey, token)
    
    // 验证设置是否成功
    const cookieCheck = Cookies.get(TokenKey)
    const localCheck = localStorage.getItem(TokenKey)
    
    console.log('Cookie设置结果:', cookieCheck ? '成功' : '失败')
    console.log('localStorage设置结果:', localCheck ? '成功' : '失败')
    
    return cookieCheck || localCheck
  } catch (error) {
    console.error('Token设置失败:', error)
    
    // 如果Cookie设置失败，至少确保localStorage设置成功
    try {
      localStorage.setItem(TokenKey, token)
      console.log('使用localStorage作为备用存储')
      return localStorage.getItem(TokenKey) === token
    } catch (localError) {
      console.error('localStorage也设置失败:', localError)
      return false
    }
  }
}

export function removeToken() {
  try {
    Cookies.remove(TokenKey)
    localStorage.removeItem(TokenKey)
    console.log('Token已清除')
    return true
  } catch (error) {
    console.error('Token清除失败:', error)
    return false
  }
}
